package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Comment;
import util.DBHelp;
import util.RowMapper;

public class CommentDao {

    private DBHelp<Comment> db = new DBHelp<Comment>();

    public List<Comment> findByIdeaId(int ideaId) {
        String sql = "SELECT bmw_comment.id,context,TIME,bmw_idea_id,bmw_user_id,bmw_user.name AS bmw_user_name FROM bmw_comment,bmw_user WHERE bmw_user_id = bmw_user.id AND bmw_idea_id = ? ORDER BY TIME DESC";
        return db.excuteForList(sql, new CommentRowMapper(), ideaId);
    }
    
    public int delComment(int id) {
        String sql = "delete from bmw_comment where id = ?";
        return db.excuteSQL(sql, id);
    }
    
    public int delCommentByIdeaId(int ideaId) {
        String sql = "delete from bmw_comment where bmw_idea_id = ?";
        return db.excuteSQL(sql, ideaId);
    }

    public int addComment(Comment comment) {
        String sql = "insert into bmw_comment(context, time, bmw_idea_id, bmw_user_id) value(?,?,?,?)";
        return db.excuteSQL(sql, comment.getContext(),
                System.currentTimeMillis(), comment.getIdeaId(),
                comment.getUserId());
    }

    private class CommentRowMapper implements RowMapper<Comment> {

        @Override
        public Comment mapperRow(ResultSet rs) throws SQLException {

            Comment comment = new Comment();
            comment.setId(rs.getInt("id"));
            comment.setContext(rs.getString("context"));
            comment.setTime(rs.getLong("time"));
            comment.setIdeaId(rs.getInt("bmw_idea_id"));
            comment.setUserId(rs.getInt("bmw_user_id"));
            comment.setUserName(rs.getString("bmw_user_name"));
            return comment;
        }

    }
}
